// Switcher3 插件 API 路由
module.exports = (router, projectManager) => {
  
  // 提供Whistle规则 - 用于@whistle.switcher3/cgi-bin/rules
  router.get('/cgi-bin/rules', async (ctx) => {
    try {
      console.log('[Switcher3] Whistle请求规则');
      
      const rules = generateWhistleRules(projectManager);
      
      console.log('[Switcher3] 返回规则给Whistle:', rules);
      
      // 设置响应头为纯文本
      ctx.set('Content-Type', 'text/plain; charset=utf-8');
      ctx.set('Cache-Control', 'no-cache');
      
      ctx.body = rules;
    } catch (error) {
      console.error('[Switcher3] 生成Whistle规则失败:', error);
      ctx.set('Content-Type', 'text/plain; charset=utf-8');
      ctx.body = '# Switcher3 Rules Generation Error\n# ' + error.message + '\n';
    }
  });
  
  // 提供Whistle规则 - 用于@whistle.switcher3/api/rules
  router.get('/api/rules', async (ctx) => {
    try {
      console.log('[Switcher3] 生成Whistle规则');
      
      const rules = generateWhistleRules(projectManager);
      
      console.log('[Switcher3] 生成的Whistle规则:', rules);
      
      // 设置响应头为纯文本
      ctx.set('Content-Type', 'text/plain; charset=utf-8');
      ctx.set('Cache-Control', 'no-cache');
      
      ctx.body = rules;
    } catch (error) {
      console.error('[Switcher3] 生成Whistle规则失败:', error);
      ctx.set('Content-Type', 'text/plain; charset=utf-8');
      ctx.body = '# Switcher3 Rules Generation Error\n';
    }
  });
  
  // 获取项目列表
  router.get('/cgi-bin/projects', async (ctx) => {
    try {
      console.log('[Switcher3] 收到获取项目列表请求');
      const result = projectManager.getProjectList();
      console.log('[Switcher3] 项目列表结果:', result);
      ctx.body = result;
    } catch (error) {
      console.error('[Switcher3] API获取项目列表失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  });

  // 获取单个项目详情
  router.get('/cgi-bin/projects/:projectId', async (ctx) => {
    try {
      const { projectId } = ctx.params;
      const result = projectManager.getProject(projectId);
      ctx.body = result;
    } catch (error) {
      console.error('[Switcher3] API获取项目详情失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  });

  // 创建新项目
  router.post('/cgi-bin/projects', async (ctx) => {
    try {
      const { name } = ctx.request.body;
      const result = await projectManager.createProject(name);
      ctx.body = result;
    } catch (error) {
      console.error('[Switcher3] API创建项目失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  });

  // 重命名项目
  router.put('/cgi-bin/projects/:projectId/rename', async (ctx) => {
    try {
      const { projectId } = ctx.params;
      const { name } = ctx.request.body;
      const result = await projectManager.renameProject(projectId, name);
      ctx.body = result;
    } catch (error) {
      console.error('[Switcher3] API重命名项目失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  });

  // 删除项目
  router.delete('/cgi-bin/projects/:projectId', async (ctx) => {
    try {
      const { projectId } = ctx.params;
      const result = await projectManager.deleteProject(projectId);
      ctx.body = result;
    } catch (error) {
      console.error('[Switcher3] API删除项目失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  });

  // 更新环境配置
  router.put('/cgi-bin/projects/:projectId/environments/:environment', async (ctx) => {
    try {
      const { projectId, environment } = ctx.params;
      const { config } = ctx.request.body;
      const result = await projectManager.updateEnvironmentConfig(projectId, environment, config);
      ctx.body = result;
    } catch (error) {
      console.error('[Switcher3] API更新环境配置失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  });

  // 激活环境
  router.post('/cgi-bin/projects/:projectId/environments/:environment/activate', async (ctx) => {
    try {
      const { projectId, environment } = ctx.params;
      const result = await projectManager.activateEnvironment(projectId, environment);
      ctx.body = result;
    } catch (error) {
      console.error('[Switcher3] API激活环境失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  });

  // 停用环境
  router.post('/cgi-bin/projects/:projectId/environments/deactivate', async (ctx) => {
    try {
      const { projectId } = ctx.params;
      const result = await projectManager.deactivateEnvironment(projectId);
      ctx.body = result;
    } catch (error) {
      console.error('[Switcher3] API停用环境失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  });

  // 添加自定义规则
  router.post('/cgi-bin/projects/:projectId/custom-rules', async (ctx) => {
    try {
      const { projectId } = ctx.params;
      const { label, value } = ctx.request.body;
      const result = await projectManager.addCustomRule(projectId, label, value);
      ctx.body = result;
    } catch (error) {
      console.error('[Switcher3] API添加自定义规则失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  });

  // 更新自定义规则
  router.put('/cgi-bin/projects/:projectId/custom-rules/:ruleId', async (ctx) => {
    try {
      const { projectId, ruleId } = ctx.params;
      const updates = ctx.request.body;
      const result = await projectManager.updateCustomRule(projectId, ruleId, updates);
      ctx.body = result;
    } catch (error) {
      console.error('[Switcher3] API更新自定义规则失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  });

  // 删除自定义规则
  router.delete('/cgi-bin/projects/:projectId/custom-rules/:ruleId', async (ctx) => {
    try {
      const { projectId, ruleId } = ctx.params;
      const result = await projectManager.deleteCustomRule(projectId, ruleId);
      ctx.body = result;
    } catch (error) {
      console.error('[Switcher3] API删除自定义规则失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  });

  // 激活自定义规则
  router.post('/cgi-bin/projects/:projectId/custom-rules/:ruleId/activate', async (ctx) => {
    try {
      const { projectId, ruleId } = ctx.params;
      const result = await projectManager.activateEnvironment(projectId, `custom:${ruleId}`);
      ctx.body = result;
    } catch (error) {
      console.error('[Switcher3] API激活自定义规则失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  });

  // 获取统计信息
  router.get('/cgi-bin/stats', async (ctx) => {
    try {
      const result = projectManager.getStats();
      ctx.body = result;
    } catch (error) {
      console.error('[Switcher3] API获取统计信息失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  });

  // 获取激活的环境列表
  router.get('/cgi-bin/active-environments', async (ctx) => {
    try {
      const activeEnvironments = projectManager.dataStorage.getActiveEnvironments();
      ctx.body = {
        success: true,
        data: activeEnvironments
      };
    } catch (error) {
      console.error('[Switcher3] API获取激活环境失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  });

  // 重置所有配置（开发调试用）
  router.post('/cgi-bin/reset', async (ctx) => {
    try {
      const result = await projectManager.reset();
      ctx.body = result;
    } catch (error) {
      console.error('[Switcher3] API重置配置失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  });

  // 健康检查
  router.get('/cgi-bin/health', async (ctx) => {
    ctx.body = {
      success: true,
      message: 'Switcher3 插件运行正常',
      timestamp: new Date().toISOString(),
      version: '1.0.0'
    };
  });

  // 获取插件信息
  router.get('/cgi-bin/info', async (ctx) => {
    try {
      const stats = projectManager.getStats();
      ctx.body = {
        success: true,
        data: {
          name: 'Switcher3',
          version: '1.0.0',
          description: 'Whistle多项目环境配置管理插件',
          ...stats.data
        }
      };
    } catch (error) {
      console.error('[Switcher3] API获取插件信息失败:', error);
      ctx.status = 500;
      ctx.body = {
        success: false,
        error: error.message
      };
    }
  });
};

/**
 * 生成Whistle规则
 */
function generateWhistleRules(projectManager) {
  const rules = [];
  
  // 添加规则头部注释
  rules.push('# Switcher3 Plugin Generated Rules');
  rules.push('# Generated at: ' + new Date().toISOString());
  rules.push('');
  
  try {
    // 获取所有激活的环境
    const activeEnvResult = projectManager.getActiveEnvironments();
    
    if (!activeEnvResult.success) {
      rules.push('# Failed to get active environments');
      return rules.join('\n');
    }
    
    const activeEnvironments = activeEnvResult.data;
    console.log('[Switcher3] 激活的环境数量:', activeEnvironments.length);
    
    if (activeEnvironments.length === 0) {
      rules.push('# No active environments');
      return rules.join('\n');
    }
    
    // 为每个激活的环境生成规则
    activeEnvironments.forEach(env => {
      const projectResult = projectManager.getProject(env.projectId);
      if (!projectResult.success) {
        console.log(`[Switcher3] 获取项目失败: ${env.projectId}`);
        return;
      }
      
      const project = projectResult.data;
      
      rules.push('');
      rules.push(`# Project: ${project.name}`);
      rules.push(`# Environment: ${env.environment}`);
      rules.push(`# Activated at: ${env.activatedAt}`);
      
      // 获取环境配置
      let configContent = '';
      if (env.environment === 'test') {
        configContent = project.environments.test;
      } else if (env.environment === 'production') {
        configContent = project.environments.production;
      } else if (env.environment.startsWith('custom:')) {
        const ruleId = env.environment.substring(7);
        const rule = project.customRules.find(r => r.id === ruleId);
        if (rule) {
          configContent = rule.value;
          rules.push(`# Custom Rule: ${rule.name}`);
        }
      }
      
      if (configContent && configContent.trim()) {
        // 解析配置内容并生成规则
        const configLines = configContent.split('\n');
        
        configLines.forEach(line => {
          line = line.trim();
          
          // 跳过空行和注释行
          if (!line || line.startsWith('#')) {
            if (line) {
              rules.push(line); // 保留用户的注释
            }
            return;
          }
          
          // 解析域名映射规则（用户输入格式：IP地址 域名）
          const parts = line.split(/\s+/);
          if (parts.length >= 2) {
            const target = parts[0];  // IP地址或IP:端口
            const domain = parts[1];  // 域名
            
            // 生成Whistle规则格式（域名 IP地址）
            const whistleRule = `${domain} ${target}`;
            rules.push(whistleRule);
            
            console.log(`[Switcher3] 生成规则: ${whistleRule}`);
          }
        });
      } else {
        rules.push(`# ${project.name} - ${env.environment}: No configuration`);
      }
    });
    
  } catch (error) {
    console.error('[Switcher3] 生成规则失败:', error);
    rules.push('# Error generating rules: ' + error.message);
  }
  
  const result = rules.join('\n');
  console.log('[Switcher3] 最终生成的规则:\n', result);
  return result;
}
